import {
  AfterViewInit,
  Component,
  ElementRef,
  OnInit,
  Renderer2,
  ViewChild,
} from '@angular/core';
import { OrganizationTypeEnum } from '../../domain/sparrow';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OrganizationSearchComponent } from 'src/app/share/organization-search/organization-search.component';
import { NzMessageService } from 'ng-zorro-antd/message';
import {
  Pageable,
  Organization,
  OrganizationService,
} from 'sparrow-permission-lib';
import { map, switchMap } from 'rxjs/operators';
import { of, zip } from 'rxjs';

@Component({
  selector: 'app-organization',
  templateUrl: './organization.component.html',
  styleUrls: ['./organization.component.css'],
})
export class OrganizationComponent implements OnInit, AfterViewInit {
  modelName?: string;
  selectedOrg: any = {}; //选中的组织
  isRoot!: boolean;
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private orgService: OrganizationService,
    private render: Renderer2
  ) {}
  ngAfterViewInit(): void {
    let pageable: Pageable = { page: 0, size: 50, sort: ['createdDate,desc'] };
    const divRoot = this.render.createElement('div');
    this.render.appendChild(this.testDiv.nativeElement, divRoot);
    this.loadCustomTree(divRoot, 'root', pageable, 1);
  }

  @ViewChild('testDiv') testDiv!: ElementRef;
  childrentMap!: Map<any, any[]>;
  isLoadAll: boolean = false;

  ngOnInit(): void {
    this.childrentMap = new Map();
  }

  loadCustomTree(
    divParent: any,
    divParentId: string,
    pageable: Pageable,
    level: number
  ) {
    let parentId: string =
      divParentId.indexOf('_') < 0 ? divParentId : divParentId.split('_')[0];
    //获取根组织
    this.orgService
      .getChildren1(parentId, 'ORGANIZATION', pageable)
      .subscribe((res) => {
        // 如果没有加载全部，则提示继续加载
        const divLoadMore = this.render.createElement('div');
        if (!res.last && !this.isLoadAll) {
          let leftCount =
            res.totalElements! - (pageable.page! + 1) * pageable.size!;
          const divDown = this.render.createElement('div');
          const divDoubleDown = this.render.createElement('div');
          this.render.addClass(divDown, 'arrowdown');
          this.render.addClass(divDoubleDown, 'double-arrowdown');

          this.render.appendChild(divLoadMore, divDown);
          this.render.appendChild(
            divLoadMore,
            this.render.createText(
              '' + (pageable.size! < leftCount ? pageable.size! : leftCount)
            )
          );

          this.render.appendChild(divLoadMore, divDoubleDown);
          this.render.appendChild(
            divLoadMore,
            this.render.createText('' + leftCount)
          );

          this.render.addClass(divLoadMore, 'load-more');
          // 按页加载
          this.render.listen(divDown, 'click', (event) => {
            this.render.removeChild(divParent, divLoadMore);
            let pageableLoadMore: Pageable = {
              page: pageable.page! + 1,
              size: pageable.size,
              sort: pageable.sort,
            };
            // console.log('=======', pageableLoadMore);
            this.loadCustomTree(
              divParent,
              divParentId,
              pageableLoadMore,
              level
            );
          });

          // 加载所有
          this.render.listen(divDoubleDown, 'click', (event) => {
            this.isLoadAll = true;
            this.render.removeChild(divParent, divLoadMore);
            for (
              let i = res.pageable?.pageNumber! + 1;
              i <= res.totalPages!;
              i = i + 1
            ) {
              let pageableLoadMore: any = {
                page: i,
                size: pageable.size,
                sort: pageable.sort,
              };
              // console.log('=======', pageableLoadMore);
              this.loadCustomTree(
                divParent,
                divParentId,
                pageableLoadMore,
                level
              );
            }
          });
        }
        res.content!.forEach((f: any) => {
          // 名称(子数量)
          const divNode = this.render.createElement('div');
          this.render.appendChild(divParent, divNode);

          if (this.childrentMap.get(divParentId) === undefined) {
            this.childrentMap.set(divParentId, []);
          }
          this.childrentMap.get(divParentId)!.push(divNode); // 保存所有的子节点，用于折叠展开使用
          // console.log('%%%%%%%%', divParentId)

          // 组织名称
          const spanName = this.render.createElement('span');
          this.render.setAttribute(
            spanName,
            'id',
            parentId === 'root' ? f.id : f.id.organizationId + '_' + divParentId
          );
          // 获取组织详情
          this.render.listen(spanName, 'click', (event) => {
            // 获取上级组织
            let parentIdForDetail: string =
              event.target.id.indexOf('_') < 0
                ? event.target.id
                : event.target.id.split('_')[0];
            this.orgService.get4(parentIdForDetail).subscribe((orgDetail) => {
              this.selectedOrg = orgDetail;
              this.orgService
                .getParents1(this.selectedOrg.id)
                .pipe(
                  switchMap((orgRelations) =>
                    zip(
                      ...orgRelations.map((orgRelation: any) =>
                        this.orgService.get4(orgRelation.id?.parentId)
                      )
                    )
                  )
                )
                .subscribe((res) => {
                  this.selectedOrg.parents = res;
                  if (this.selectedOrg.isRoot) {
                    this.selectedOrg.parents.push({ name: '根', id: 'root' });
                  }
                });
            });
          });

          // 获取下级组织的数量
          this.orgService
            .getChildren1(
              parentId === 'root' ? f.id : f.id.organizationId,
              'ORGANIZATION',
              { page: 0, size: 1 }
            )
            .subscribe((childCould) => {
              if (parentId === 'root') {
                this.render.appendChild(
                  spanName,
                  this.render.createText(
                    f.name + '(' + childCould.totalElements + ')'
                  )
                );
                this.render.setStyle(spanName, 'font-weight', 'bold');
              } else {
                // 当有下级的时候，不缩进，对对齐同级
                if (childCould.totalElements! > 0) {
                  this.render.setStyle(divNode, 'padding-left', 14 + 'px');
                } else {
                  this.render.setStyle(divNode, 'padding-left', 14 + 14 + 'px');
                }
                this.orgService
                  .get4(f.id.organizationId)
                  .subscribe((organization) => {
                    this.render.appendChild(
                      spanName,
                      this.render.createText(
                        organization.name +
                          (childCould.totalElements! > 0
                            ? '(' + childCould.totalElements + ')'
                            : '')
                      )
                    );
                    if (organization.type === 'ORGANIZATION') {
                      this.render.setStyle(spanName, 'font-weight', 'bold');
                    }
                  });
              }

              //当有下级组织时，展开
              if (childCould.totalElements! > 0) {
                // 展开按钮
                const spanExpand = this.render.createElement('span');
                this.render.setAttribute(
                  spanExpand,
                  'id',
                  parentId === 'root'
                    ? f.id
                    : f.id.organizationId + '_' + divParentId
                );
                this.render.appendChild(
                  spanExpand,
                  this.render.createText('+')
                );
                this.render.addClass(spanExpand, 'expand');
                // 当点击展开时，获取子组织
                this.render.listen(spanExpand, 'click', (event) => {
                  let parentId1: string = event.target.id; //.indexOf('_')<0? event.target.id: event.target.id.split('_')[1];
                  // console.log('&&&&&&&&&&&',event.target.id,event.target.id.indexOf('_'),parentId1,event.target.id.split('_'));
                  if (event.target.innerText === '+') {
                    event.target.innerText = '-';

                    if (
                      (this.childrentMap.get(parentId1) != undefined &&
                        this.childrentMap.get(parentId1)!.length > 0) ||
                      parentId1 === 'root'
                    ) {
                      // 已经加载过了，无需再次加载，直接展开
                      this.childrentMap.get(parentId1)?.forEach((f) => {
                        this.render.setStyle(f, 'display', 'block');
                      });
                    } else {
                      // 首次展开
                      this.loadCustomTree(
                        divNode,
                        parentId1,
                        { page: 0, size: pageable.size, sort: pageable.sort },
                        level + 1
                      );
                    }
                  } else {
                    // 折叠下级
                    event.target.innerText = '+';
                    // console.log('*************', divParent);
                    this.childrentMap.get(parentId1)?.forEach((f) => {
                      this.render.setStyle(f, 'display', 'none');
                    });
                  }
                });
                this.render.appendChild(divNode, spanExpand);
                // this.render.insertBefore(divParent, divLoadMore, divNode);
              }
              this.render.appendChild(divNode, spanName);
              // this.render.appendChild(divParent, divNode);
              this.render.appendChild(divParent, divLoadMore);
            });
        });
      });
  }

  delOrganization(selectedOrg1: any) {
    this.orgService.delete2([selectedOrg1.id],'response').subscribe((res) => {
      if(res.status!=204){
        this.message.error("删除失败" + res.body)
      }else{
        window.location.href = '/organization'
      }
      // this.message.success('删除成功！');
      // window.location.href = '/organization'
    });
  }

  // 取消组织关系，上级
  onTagClose(s: any) {
    if (this.selectedOrg.parents.length === 1) {
      this.message.info('没有其他上级组织，不允许取消根上级！');
    } else {
      this.orgService
        .removeParent(this.selectedOrg.id, [s.id],'response')
        .subscribe((res) => {
          if(res.status!=204)
            this.message.error('取消失败！');
        });
    }
  }

  // for new organization
  validateForm!: FormGroup;
  selectedItem: { name?: string; code?: string } = {};
  @ViewChild(OrganizationSearchComponent)
  organizationSearch!: OrganizationSearchComponent;
  submitForm() {

    const parentIds$ = this.organizationSearch?.selectedParent.map(
      (s) => s.id!
    );

    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let organization: Organization = this.validateForm.value;
      console.log(parentIds$);
      if (parentIds$?.length === 0) {
        organization.isRoot = true;
      } else {
        organization.isRoot = false;
      }
      if (organization.id === undefined) {
        this.orgService.create3(organization).pipe(
          switchMap((org: any)=>parentIds$.length>0?this.orgService.addParent(org.id!, parentIds$):of({}))
        )
        .subscribe(
          (res) => {
            this.message.success('添加成功！');
            this.isVisibleForNewModal = false;
            window.location.href = '/organization'
          },
          (error) => {
            console.log(error);
            this.message.error("添加失败" + error)
          }
        );
      } else {
        let updateOrg: any = {};
        if (this.selectedOrg.name != organization.name) {
          updateOrg.name = organization.name;
        }
        if (this.selectedOrg.code != organization.code) {
          updateOrg.code = organization.code;
        }
        if (this.selectedOrg.type != organization.type) {
          updateOrg.type = organization.type;
        }
        this.orgService.update3(organization.id, updateOrg).subscribe(
          (res) => {
            organization = res;
            this.isVisibleForNewModal = false;
            this.message.success('更新成功！');
            window.location.href = '/organization'
          },
          (error) => {
            console.log(error);
          }
        );
      }
    }
  }

  organizationTypes: any[] = Object.keys(OrganizationTypeEnum).map((label) => ({
    label: OrganizationTypeEnum[label as keyof typeof OrganizationTypeEnum],
    value: label,
  }));

  isVisibleForNewModal: boolean = false;
  opAction!: string;
  showNewModal(node: any | null) {
    this.isVisibleForNewModal = true;

    if (node === null) {
      this.validateForm = this.fb.group({
        name: [null, [Validators.required]],
        code: [null, [Validators.required]],
        type: [null, [Validators.required]],
      });
      this.opAction = 'add';
    } else {
      this.validateForm = this.fb.group({
        name: [node.name, [Validators.required]],
        code: [node.code, [Validators.required]],
        type: [node.type, [Validators.required]],
        id: [node.id, [Validators.required]],
      });
      this.opAction = 'edit';
    }
  }

  handleCancel() {
    this.isVisibleForNewModal = false;
    this.isVisibleForSetParent = false;
  }

  // 设置上级机构
  isVisibleForSetParent: boolean = false;
  showParentDlg() {
    this.isVisibleForSetParent = true;
  }

  setParent() {
    const parentIds$: string[] = this.organizationSearch.selectedParent.map(
      (s) => s.id!
    );
    if (this.selectedOrg.isRoot) {
      parentIds$.push('root');
    }
    this.orgService
      .addParent(this.selectedOrg.id, parentIds$,'response')
      .subscribe((res) => {
        if(res.status===204){
          this.isVisibleForSetParent = false;
          this.message.success('设置成功！');
          window.location.href = '/organization'
        }
      });
  }
}
